// 生成唯一文件名
function generateUniqueFileName(filePath) {
    const tempId = Date.now();
    // 简单拼接生成唯一文件名
    return `${tempId}_${filePath.replace(/[^a-zA-Z0-9]/g, '')}.jpg`;
}

// 封装文件上传和获取临时 URL 的函数
// 封装文件上传和获取临时 URL 的函数
var  percent=0
async function uploadAndGetTempUrl(filePath, cloudPath) {

    try {
        // 上传开始时显示加载框
        uni.showLoading({
            title: `${percent}%`
        });

        const uploadResult = await uniCloud.uploadFile({
            filePath,
            cloudPath,
            onUploadProgress: function (progressEvent) {
                  percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
		
                // 更新加载框的提示信息
	             
      
            }
        });

        const urlRes = await uniCloud.getTempFileURL({
            fileList: [uploadResult.fileID]
        });

        // 上传完成后隐藏加载框
      
        return urlRes.fileList[0].tempFileURL;
    } catch (error) {
        // 出现错误时隐藏加载框
   
        console.error('上传或获取临时 URL 失败:', error);
        throw error;
    }
}

export const Images = async () => {
    let imagePaths = [];
    let uploadedImageUrls = [];
    try {
        const res = await new Promise((resolve, reject) => {
            uni.chooseMedia({
                count: 9,
                mediaType: ['image'],
                sizeType: ['compressed'],
             //   sourceType: ['camera','album'],
             
                success: (res) => {
				    resolve(res);
                },
                fail: (err) => {
                    console.error('选择图片失败:', err);
                    reject(err);
                }
            });
        });
        console.log("摄像" + JSON.stringify(res));
        imagePaths = res.tempFiles;

        const batchSize = 3;
        const totalImages = imagePaths.length;
        const totalBatches = Math.ceil(totalImages / batchSize);

        for (let i = 0; i < totalBatches; i++) {
            const start = i * batchSize;
            const end = Math.min((i + 1) * batchSize, totalImages);
            const batchPaths = imagePaths.slice(start, end);

            const uploadTasks = batchPaths.map((filePath) => {
                const uniqueFileName = generateUniqueFileName(filePath.tempFilePath);
                const cloudPath = `mediaMsg/${uniqueFileName}`;
                return uploadAndGetTempUrl(filePath.tempFilePath, cloudPath);
            });

            const batchUrls = await Promise.all(uploadTasks);
            uploadedImageUrls = uploadedImageUrls.concat(batchUrls);
            console.log(`第 ${i + 1} 批图片上传完成，获取到的图片地址:`, batchUrls);
        }

        uni.showToast({
            title: '图片上传完成',
            icon: 'success'
        });
        return uploadedImageUrls;
    } catch (e) {
        console.log(e);
        handleError('选择图片失败', e);
        return [];
    }
};

export const Video = async () => {
    let videoPaths = {
        videoPath: "",
        videoPic: ''
    };
    try {
        // 选择视频
        const res = await new Promise((resolve, reject) => {
            uni.chooseMedia({
                count: 1,
                mediaType: ['video'],
                maxDuration: 30,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                camera: "back",
                success: (res) => {
                    resolve(res);
                },
                fail: (err) => {
                    reject(err);
                }
            });
        });

        const tempVideo = res;
        console.log("tempVideo: " + JSON.stringify(tempVideo));

        // 上传视频
        uni.showLoading({
            title: '视频上传中...'
        });
        const video = tempVideo.tempFiles[0].tempFilePath;
        const videoCloudPath = `${Date.now()}`;
        videoPaths.videoPath = await uploadAndGetTempUrl(video, `/videoTempFilePath/${videoCloudPath}.mp4`);

        // 上传视频缩略图
        const videoPic = tempVideo.tempFiles[0].thumbTempFilePath;
        const picCloudPath = `${Date.now()}`;
        videoPaths.videoPic = await uploadAndGetTempUrl(videoPic, `/videoTempFilePath/${picCloudPath}.jpg`);

        uni.hideLoading();
        console.log("视频和缩略图的临时访问 URL 已获取", videoPaths);
        return videoPaths;
    } catch (error) {
        uni.hideLoading();
        console.error("操作出错:", error);
        handleError('选择或上传视频失败', error);
    }
};

function handleError(message, error) {
    let errorMsg = message;
    if (error.code === 'NETWORK_ERROR') {
        errorMsg = '网络错误，请检查网络连接';
    } else if (error.code === 'UPLOAD_FAILED') {
        errorMsg = '上传失败，请稍后重试';
    }
    console.log(errorMsg, error);
    uni.showToast({
        title: errorMsg,
        icon: 'none'
    });
}
